package com.minshenglife.zanzan.web.weixin;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.minshenglife.commons.security.utils.AccessTokenUtils;
import com.minshenglife.commons.security.utils.pp.UserIdentify;
import com.minshenglife.commons.security.utils.pp.UserIdentify.UserType;
import com.minshenglife.zanzan.entity.AccessTokenAndJsapiTicket;
import com.minshenglife.zanzan.entity.User;
import com.minshenglife.zanzan.pub.Config;
import com.minshenglife.zanzan.pub.message.custservice.GetAccessTokenMessage;
import com.minshenglife.zanzan.pub.utils.HttpUtil;
import com.minshenglife.zanzan.pub.utils.Message;
import com.minshenglife.zanzan.pub.utils.SignUtil;
import com.minshenglife.zanzan.pub.utils.WXKeys;
import com.minshenglife.zanzan.service.AccessTokenAndJsapiTicketService;
import com.minshenglife.zanzan.service.AccessTokenService;
import com.minshenglife.zanzan.service.UserService;
import com.minshenglife.zanzan.web.service.RequestTaskService;
import com.minshenglife.zanzan.web.weixin.form.CoreForm;
import com.minshenglife.zanzan.web.weixin.model.WXUserInfo;
import com.minshenglife.zanzan.web.weixin.service.CoreService;
import com.minshenglife.zanzan.web.weixin.service.WXAccTokenService;
import com.minshenglife.zanzan.web.weixin.service.WXBaseService;
import com.nationsky.pub.utils.DateUtils;
import com.nationsky.pub.utils.StringUtils;

import net.sf.json.JSONObject;


/**
 * 
 * @author huodd 
 * 
 */
@Controller
@RequestMapping("/core")
public class CoreController extends BaseController {
	Logger log = LoggerFactory.getLogger(CoreController.class);
	
	@Resource
	CoreService coreService;
	@Resource
	UserService userService;
	@Resource
	AccessTokenService accessTokenService;
	@Resource
	WXAccTokenService tokenService;
	
	@Resource
	AccessTokenAndJsapiTicketService service;
	
	@RequestMapping("/main.do")
	@ResponseBody
	public void main(HttpServletRequest request,HttpServletResponse response){
		log.info("===========log start===main");
		// 随机字符串
        String echostr = request.getParameter("echostr");  
       
        try {
        	PrintWriter out;
			out = response.getWriter();
	        if(echostr==null || "".equals(echostr)){
	        	//
	            String respMessage = coreService.processRequest(request);  
	            System.out.println("---------main------end"+respMessage);
	            respMessage=com.minshenglife.zanzan.pub.utils.StringUtils.replaceBlank(respMessage);
	            System.out.println("---------replaceBlank------end"+respMessage);
				out.print(respMessage);  
	        }else{
	            String timestamp = request.getParameter("timestamp");  
	            String nonce = request.getParameter("nonce");  
	            String signature = StringUtils.processStrings(request.getParameter("signature"));
		        // 校验signature，成功后返回echostr
		        if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
		        	out.print(echostr);  
		        }
	        }
	        out.close();  
        } catch (IOException e) {
			e.printStackTrace();
		}  
        log.info("===========log end===main");
	}
	@RequestMapping("/test.do")
	@ResponseBody
	public Message sendTestData(){
		String url="http://127.0.0.1:8080/core/main.do";
		String data="<xml>"+
		"<ToUserName><![CDATA[toUser]]></ToUserName>"+
		"<FromUserName><![CDATA[fromUser]]></FromUserName>"+
		"<CreateTime>1348831860</CreateTime>"+
		"<MsgType><![CDATA[text]]></MsgType>"+
		"<Content><![CDATA[this is a test]]></Content>"+
		"<MsgId>1234567890123456</MsgId>"+
		"</xml>";
		System.out.println("----------request-----xml"+data);
		String respMessage="";
		try {
//			InputStream inputStream=RequestTaskService.sendDataStream2(url, data);
//			respMessage = coreService.processRequestOfTest(inputStream);  
			respMessage=RequestTaskService.sendDataStream(url, data);
			
	            System.out.println("----------sendTestData-----end"+respMessage);
			
		} catch (Exception e) {
			e.printStackTrace();
			return new Message(Message.STATE_one,"error");
		}
		return new Message(Message.STATE_200,respMessage);
	}

	@RequestMapping("/toPageDoor.do")
	public void toPageDoor(HttpServletRequest request,HttpServletResponse response,
			CoreForm coreForm){
		log.info("===========log start===topagedoor");
		String action="/core/toPageDoor.do";
		String redirectUrl=WXKeys.WX_BASEURL+action;
		log.debug(request.getRequestURI());
		try {
			//用户同意授权，获取code
			if(!StringUtils.isNullOrEmpty(coreForm.getKey())){
				log.debug("用户同意授权，获取code");
				String url=WXBaseService.getCodeByAuthorizeUrl(redirectUrl, false, null,coreForm.getKey());
				log.debug(url);
				response.sendRedirect(url);
			}
			//通过code换取网页授权access_token
			else if(!StringUtils.isNullOrEmpty(coreForm.getState()) && !StringUtils.isNullOrEmpty(coreForm.getCode())){
				log.debug("通过code换取网页授权access_token");
				GetAccessTokenMessage msg=WXBaseService.getAccessTokenByCode(coreForm.getCode());
				if(msg!=null){
					String openId=msg.getOpenid();
					if(!StringUtils.isNullOrEmpty(openId)){
						 String topage=toWebPage(coreForm.getState(),openId,response,msg.getUnionid());
						 log.debug(topage);
						 response.sendRedirect(topage);
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		log.info("===========log end===topagedoor");
	}
	
	
	/**
	 * 处理菜单事件
	 * @param key 事件key值
	 * @param access_token 事件请求者的微信号access_token
	 * @param baseUrl 
	 * @return
	 */
	private String toWebPage(String key,String userOpenId,HttpServletResponse response,String unionId) {
		//校验请求者是否已经绑定员工号 
		User user=userService.getUserByWXCode(userOpenId);
		if(user!=null&&unionId!=null&&unionId.trim().length()!=0){
			if(user.getUnionId()==null||user.getUnionId().trim().equals("")){
				User thisUser = new User();
				thisUser.setEmpId(user.getEmpId());
				thisUser.setUnionId(unionId);
				userService.updateUserInfo(thisUser);
			}
		}
		String access_token=null;
		if(user!=null){
		 access_token=AccessTokenUtils.newToken(new UserIdentify(UserType.weixin,userOpenId), user.getIdNo());
		 accessTokenService.insertAccessToken(user,access_token);//插入页面时效
		}
		String toPage="";
		if(user==null){
			//用时间串生成access_token
			 access_token=AccessTokenUtils.newToken(new UserIdentify(UserType.weixin,userOpenId), String.valueOf(new Date().getTime()));
			 accessTokenService.insertAccessTokenOfNotUser(userOpenId,access_token);//插入页面时效
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/register.jsp?access_token="+access_token;
		}
		else if(WXKeys.WX_ZZMSR_BTN_MENU_REDRANKING.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/redFlowerRank.jsp?access_token="+access_token;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_SENDRANKING.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/sendFlowerRank.jsp?access_token="+access_token;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_PROGRESSRANKING.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/progressRank.jsp?access_token="+access_token;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_INTEGRALRANKING.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/integralRank.jsp?access_token="+access_token;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_MYREDFLOWER.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/myFlower.jsp?access_token="+access_token;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_MYTEGRAL.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/myIntegral.jsp?access_token="+access_token;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_TOSENDFLOWER.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/searchEmp.jsp?access_token="+access_token;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_MYTOCAO.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/myEndPlate.jsp?access_token="+access_token;;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_MYREVIEW.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/myReview.jsp?access_token="+access_token;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_MYINFO.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/myInfo.jsp?access_token="+access_token;
		}
		else if(WXKeys.WX_ZZMSR_BTN_MENU_WORKCON.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/workConMainPage.jsp?access_token="+access_token+"&userPostId="+user.getPostId();
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_GAME.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/gameHall.jsp?access_token="+access_token;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_TUCAO.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/endPlateList.jsp?access_token="+access_token;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_NEWTHING.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/freshNews.jsp?access_token="+access_token;
		}else if(WXKeys.WX_ZZMSR_BTN_MENU_HELPREPLAY.equals(key)){
			toPage=WXKeys.WX_BASEURL+"/jsp/weixin/helpReplay.jsp?access_token="+access_token;
		}else{
			//请求错误页面
		}
		 return toPage;
	}
	
	/**
	 * 用于对接在微家挂链接的应用
	 * @param request
	 * @param response
	 * @param coreForm
	 */
	@RequestMapping("/toWebPageDoor.do")
	public void toWebPageDoor(HttpServletRequest request,HttpServletResponse response,
			CoreForm coreForm){
		log.info("===========log start===toWebPageDoor");
		String action="/core/toWebPageDoor.do";
		String redirectUrl=WXKeys.WX_BASEURL+action;
		log.info("redirectUrl==1=="+redirectUrl);
		log.debug(request.getRequestURI());
		redirectUrl = URLEncoder.encode(redirectUrl);
		log.info("redirectUrl==2=="+redirectUrl);
		try {
			//用户同意授权，获取code
			if(!StringUtils.isNullOrEmpty(coreForm.getKey())){
				log.debug("用户同意授权，获取code");
				log.info(request.getRequestURL().toString());
				String url=WXBaseService.getCodeByAuthorizeUrl(redirectUrl, false, null,coreForm.getKey());
				log.debug(url);
				response.sendRedirect(url);
			}
			//通过code换取网页授权access_token
			else if(!StringUtils.isNullOrEmpty(coreForm.getState()) && !StringUtils.isNullOrEmpty(coreForm.getCode())){
				log.debug("通过code换取网页授权access_token");
				GetAccessTokenMessage msg=WXBaseService.getAccessTokenByCode(coreForm.getCode());
				String errorPage=WXKeys.WX_BASEURL+"/jsp/error/error.jsp";
				if(msg!=null){
					if(msg.getErrcode()!=null&&msg.getErrcode().length()!=0){//如果有错误信息返回，则跳转过程中增加错误消息提示
						String errMsg = msg.getErrcode()+"-"+msg.getErrmsg();
						response.sendRedirect(errorPage+"?errMsg="+errMsg);
						return;
					}
					String openId=msg.getOpenid();
					String unionId = msg.getUnionid();
					System.out.println("openid=="+openId+";unionid=="+unionId+";key=="+coreForm.getState()+";code="+coreForm.getCode());
					log.info("openid=="+openId+";unionid=="+unionId+";key=="+coreForm.getState()+";code="+coreForm.getCode());
					
					if(!StringUtils.isNullOrEmpty(openId)){
						//用于获取user info
						WXUserInfo userInfo=WXBaseService.getWXUserInfo(openId,tokenService.getWXAccToken());
						if(userInfo.getErrcode().equals("40001"))
						{
							
							String accessToken=refreshAccessToken();
							userInfo=WXBaseService.getWXUserInfo(openId,accessToken);
							
						}
						
						if(userInfo==null||(userInfo.getErrcode()!=null&&userInfo.getErrcode().length()!=0)){
							String errMsg = userInfo.getErrcode()+"-"+userInfo.getErrmsg();
							response.sendRedirect(errorPage+"?errMsg="+errMsg);
							return;
						}
						if(unionId==null||unionId.length()==0){
							unionId = userInfo.getUnionid();
						}
						System.out.println(DateUtils.getCurrentTime()+":wxname="+userInfo.getNickname()+";openid=="+openId+";unionid11=="+unionId+";key=="+coreForm.getState()+";code="+coreForm.getCode());
						log.info(DateUtils.getCurrentTime()+":wxname="+userInfo.getNickname()+";openid=="+openId+";unionid11=="+unionId+";key=="+coreForm.getState()+";code="+coreForm.getCode());
						String topage = "";
						if(WXKeys.WX_ZZMSR_BTN_MENU_WJYS.equals(coreForm.getState())){
							log.info("wxname="+userInfo.getNickname()+";wximg="+userInfo.getHeadimgurl()+";wxcity="+userInfo.getCity());
							String wxname = StringUtils.isNullOrEmpty(userInfo.getNickname())?"":URLEncoder.encode(userInfo.getNickname());
							String wximg = StringUtils.isNullOrEmpty(userInfo.getHeadimgurl())?"":URLEncoder.encode(userInfo.getHeadimgurl());
							String wxcity = StringUtils.isNullOrEmpty(userInfo.getCity())?"":URLEncoder.encode(userInfo.getCity());
							topage = Config.getProperty("WX_WJJS")
									+ "?oid="+ openId
									+ "&uid="+ unionId
									+ "&time="+ System.currentTimeMillis()
									+ "&name="+ wxname
									+ "&img="+  wximg
									+ "&city="+ wxcity;
						}
						//智能宝盒
						else if(WXKeys.WX_ZZMSR_BTN_MENU_BAOHE.equals(coreForm.getState())){
							log.info("baohebaohebaohebaohe##############");
							log.info("wxname="+userInfo.getNickname()+";wximg="+userInfo.getHeadimgurl()+";wxcity="+userInfo.getCity());
							String wxname = StringUtils.isNullOrEmpty(userInfo.getNickname())?"":URLEncoder.encode(userInfo.getNickname());
							String wximg = StringUtils.isNullOrEmpty(userInfo.getHeadimgurl())?"":URLEncoder.encode(userInfo.getHeadimgurl());
							String wxcity = StringUtils.isNullOrEmpty(userInfo.getCity())?"":URLEncoder.encode(userInfo.getCity());
							topage = Config.getProperty("WX_AUTH")
									+ "?oid="+ openId
									+ "&uid="+ unionId
									+ "&time="+ System.currentTimeMillis()
									+ "&name="+ wxname
									+ "&img="+  wximg
									+ "&city="+ wxcity
									+ "&type=1";
						}
						
						else{
							topage=errorPage+"?errMsg=";
						}
						 log.debug("toPage=="+topage);
						 response.sendRedirect(topage);
					}else{
						response.sendRedirect(errorPage+"?errMsg=openIdIsNull");
					}
				}else{
					log.info("toWebPageDoor1:code="+coreForm.getCode()+";key="+coreForm.getState());
					errorPage=WXKeys.WX_BASEURL+"/jsp/error/wjyserrors.html";
					log.error("toWebPageDoor1:"+errorPage);
					response.sendRedirect(errorPage);
				}
			}else{
				log.info("toWebPageDoor:code="+coreForm.getCode()+";key="+coreForm.getState());
				String errorPage=WXKeys.WX_BASEURL+"/jsp/error/wjyserror.html";
				log.error("toWebPageDoor:"+errorPage);
				response.sendRedirect(errorPage);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		log.info("===========log end===toWebPageDoor");
	}
	
	/**
	 * 通过url刷新accessToken
	 * @param request
	 * @param response
	 * @param coreForm
	 */
	
	public String refreshAccessToken()
	{
		
		
		
		AccessTokenAndJsapiTicket ticket = new AccessTokenAndJsapiTicket();
		
		String accessToken="";
		
		String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
		access_token_url = access_token_url.replace("APPID",
				Config.getProperty("WX_APPID")).replace("APPSECRET",
				Config.getProperty("WX_SECRET"));
		log.info("请求微信获取accesstoken接口连接-->" + access_token_url);
		JSONObject jsonObject = HttpUtil.httpsRequest(access_token_url,
				"GET", null);
		log.info("*****************jsonObject************-->" + jsonObject.toString());
		if (null != jsonObject) {
			if (jsonObject.containsKey("access_token")) {
				log.info("获取access_token成功-->"
						+ jsonObject.getString("access_token"));
				String jsapiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
				String jsapiParam = "access_token=ACCESS_TOKEN&type=jsapi";
				jsapiParam = jsapiParam.replace("ACCESS_TOKEN",
						jsonObject.getString("access_token"));
				accessToken=jsonObject.getString("access_token");
				
				System.out.println("请求微信获取jsapi_ticket接口连接-->" + jsapiUrl
						+ "?" + jsapiParam);
				log.info("请求微信获取jsapi_ticket接口连接-->" + jsapiUrl + "?"
						+ jsapiParam);
				String js_api_ticket_str = HttpUtil.sendGet(jsapiUrl,
						jsapiParam);
				System.out.println("请求微信获取jsapi_ticket接口返回结果-->"
						+ js_api_ticket_str);
				log.info("请求微信获取jsapi_ticket接口返回结果-->" + js_api_ticket_str);
				if (js_api_ticket_str != null
						& !js_api_ticket_str.trim().equals("")) {
					JSONObject jsApiTicketJson = JSONObject
							.fromObject(js_api_ticket_str);
					if (jsApiTicketJson.containsKey("errcode")
							& jsApiTicketJson.getInt("errcode") == 0) {
						log.info("*******************jsApiTicketJson---ok-->"
								+ jsApiTicketJson.getString("ticket"));
						ticket.setAccessToken(jsonObject
								.getString("access_token"));
						ticket.setJsapiTicket(jsApiTicketJson
								.getString("ticket"));
						ticket.setExpiresIn(jsApiTicketJson
								.getString("expires_in"));
						ticket.setCreatetime(String.valueOf(System
								.currentTimeMillis()));
						ticket.setAppid(Config.getProperty("WX_APPID"));
						boolean isSuccess = false;
						
						isSuccess = service.updateAccessTokenAndJsapiTicket(ticket);
						
						System.out.println("isSuccess######################"+isSuccess);
						
						if (isSuccess) {
							log.info("jsapiticket ^^^^^^^^^^^^^^^accesstoken ok。。。");
						} else {
							log.error("jsapiticket ############### accesstoken error！！！");
						}
					} else {
						log.error("@@@@@@@@@@@@@@@@@@@@@@@jsApiTicketJson error-->"
								+ jsApiTicketJson.getInt("errcode") + ":"
								+ jsApiTicketJson.getString("errmsg"));
					}
				} 

			} else {
				log.error("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%:error"
						+ jsonObject.getString("errcode") + ":"
						+ jsonObject.getString("errmsg"));
			}
		}
		
		return accessToken;
		
	}
	
	
		
	
	
	
}
